
$(function(){
	var t = $('#example').DataTable({
		'sAjaxSource': 'allhomeinfotable',
		"pagingType": "full_numbers",

		//汉化
		 "language": {
             "lengthMenu": "每页 _MENU_ 条记录",
             "zeroRecords": "没有找到记录",
             "info": "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )",
             "infoEmpty": "无记录",
             "infoFiltered": "(从 _MAX_ 条记录过滤)",
             "sSearch":"搜索",
	          "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
           		 }
             },
        
		//每页显示12条数据
		pageLength: 12,
			
		columns: [{
			"data": null //此列不绑定数据源，用来显示序号
		}, {
			"data": "id"
		}, {
			"data": "headline"
		}, {
			"data": "source"
		},{
			"data":"uploader"
		},{
			"data":"date"
		},{
			"data":"type"
		}],
		"columnDefs": [{
			"targets": 7, //编辑
			"data": null,
			"defaultContent": "<button id='edit' class='btn btn-primary edit' type='button'>编辑</button>"
		}, {
			"targets": 8, //删除
			"data": null,
			"defaultContent": "<button id='delrow' class='btn btn-primary delrow btn-danger' type='button'>删除</button>"
		}, {
			"targets": 0, //第一列隐藏
			"visible": false,
			"searchable": false
		},{
			"targets": 5, 
			"render":function(data){							
				    var date = new Date(data);
				    return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
				
			}
		}
		]

	});



	//删除
	$('#example tbody').on( 'click', 'tr', function (e) {	
		if(e.target.className.match('delrow')){
			$('#myModal').modal();
			 var data=t.row( this ).data();
			 var id=data.id;
			$('#commit').click(function() {
				$.ajax({
					url: '../homeinformation/removehomeinfo',
					type: 'POST',
					data: {'id':id},
					async: true,
					success: function(data) {
						if(data === true) {
							t.ajax.reload();
						}
					},
					error: function(e) {
						console.log(e);
					}
				});

			});
		}
	
		
	});

	//编辑
	$('#example tbody').on('click', 'tr', function(e) {
		if(e.target.className.match('edit')){
			var data=t.row( this ).data();
			var id=data.id;
			$.ajax({
				url:'../homeinformation/gethomeinfobyid',
				type:'POST',
				async:true,
				data:{'id':id},
				success:function(data){	
					document.getElementById("myForm").reset(); 	
					$('input[name=id]').val(id);
					$('#form').modal();
					$('#result').empty();
					if(data.type!='图片新闻'){
						$('#picnews').hide();
					}else{
						$('#picnews').show();
					}
					//初始化编辑器
					var ue = UE.getEditor('editor');							
							ue.ready(function() {																												
							   ue.setContent(data.detail);										
							    var html = ue.getContent();										  												    
							});
							//日期格式化
							function FormatDate (strTime) {
							    var date = new Date(strTime);
							    return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
							}
							$('#datepicker').val(FormatDate(data.date));
						
							$('#type').val(data.type);										
							 $('#headline').val(data.headline);	
							 $('#uploader').val(data.uploader); 
							 $('#source').val(data.source);
							if($('#type').val()=='图片新闻')$('#result').append('<img width="300" src="'+ data.picnews +'">');
						    picnews=data.picnews;
													  																																					
							 $(function() {
								    $( "#datepicker").datepicker();
								    //汉化
								    $.datepicker.regional['zh-CN'] = {
										currentText: '今天',
										monthNames: ['一月','二月','三月','四月','五月','六月',
										'七月','八月','九月','十月','十一月','十二月'],
										monthNamesShort: ['一','二','三','四','五','六',
										'七','八','九','十','十一','十二'],
										dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
										dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
										dayNamesMin: ['日','一','二','三','四','五','六'],
										dateFormat: 'yy-mm-dd', 
										firstDay: 1,
										isRTL: false};
										$.datepicker.setDefaults($.datepicker.regional['zh-CN']);
										});	
							
					
				},
				error:function(e){
					console.log(e);
				}
			});
			
			$('#type').change(function(){
				if($(this).val()=='图片新闻'){
					$('#picnews').show();
				}else{
					$('#picnews').hide();
				}
			});
			
			var flag=false;//判断change是否被触发
			
			//上传图片预览压缩
			$('#xFile').change(function(){	
				 flag=true;
				 var MAX_HEIGHT = 500;
				var file=this.files[0];			
				if(file.size>5*1024*1024){
					alert('请选择10m以下的图片');
					return;
				}
			    if(!/image\/\w+/.test(file.type)){  
			        alert("看清楚，这个需要图片！");  
			        return;  
			    }  
			    var reader=new FileReader();
			     reader.onload = (function(file) {
			            return function(e) {		                
			              $('#result').html('<img width="300" src="'+ this.result +'" alt="'+ file.name +'" /><div class="fileName"><span class="label label-info">'+file.name+'</span></div>');	
			                base64_data=render(this.result);
			               
			                    	
			            };
			        })(file);
			      //读取文件内容
			        reader.readAsDataURL(file);
			      
			     		     
			     function render(src){		   
			     var image = new Image();
			     // 绑定 load 事件处理器，加载完成后执行
			     image.onload = compress();
			    	 
			     function compress(){		    
			     var canvas = document.getElementById("canvas");
			     // 如果高度超标
			     if(image.height > MAX_HEIGHT) {
			     // 宽度等比例缩放 *=
			     image.width *= MAX_HEIGHT / image.height;
			     image.height = MAX_HEIGHT;
			     }		  
			     var ctx = canvas.getContext("2d");
			     // canvas清屏
			     ctx.clearRect(0, 0, canvas.width, canvas.height);
			     // 重置canvas宽高
			     canvas.width = image.width;
			     canvas.height = image.height;
			     //设置背景为白色，否则会变黑
			     ctx.fillStyle = "#fff";
			     ctx.fillRect(0, 0, canvas.width, canvas.height);
			     // 将图像绘制到canvas上		     
			     ctx.drawImage(image, 0, 0, image.width, image.height);    
			     // !!! 注意，image 没有加入到 dom之中
			     var  base64=canvas.toDataURL('image/jpeg', 0.8);	
			     return base64;
			     
			     };		     		  		    
			     	image.src =src;
			     	return compress();
			      		     
			     }; 	
			    
			});
			//验证表单提交
			$().ready(function(e) {
				
				$("#myForm").validate({
					debug:true,
					rules: {
						headline: {
							required: true,
							minlength: 2,
							maxlength:50
						},
						date: {
							required: true,
							date:true
						},
						source: {
							required: true
						},
						uploader: {
							required: true
						}
					},
					messages: {
						headline: '新闻标题需要2到50个字',
						date: '请选择日期',
						source: '请填写新闻来源',
						uploader: '请填写上传者名字'
					},
					submitHandler:function(){								
						var param=$('#myForm').serialize();								
						//console.log(param);
						if($('#type').val()=='图片新闻'&&flag==true){
							var base64=base64_data.replace(/^data:image\/(png|jpeg);base64,/, "");
							base64=encodeURIComponent(base64); 
							param+='&picnews='+base64
							}else if($('#type').val()=='图片新闻'&&flag==false)
							{param+='&picnews='+picnews}else{
								param+='&picnews=null';
							}
																																			
						$.ajax({
							url:'../homeinformation/updatehomeinfo',
							type:'POST',
							data:param,
							async:true,
							success:function(data){
								$('#form').modal('hide');
								t.ajax.reload();
								
							},
							error:function(e){
								console.log(e);
							}
						});
													
					},							
				});
										
			});	
		}
																
	});
	
	//新闻类型涮选
		$('.type').click(function(){
		var val=$(this).text();
		console.log( $('#example').DataTable().column(6).data());
		 $('#example').DataTable().column(6).search(val).draw();
	});
	
	
	 
})

					